﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;

namespace Liang.DataBase.SQLiteEx
{
    public class SQLiteEx<T> : IDisposable, ISQLiteEx<T> where T : class, new()
    {
        SQLite.SQLiteConnection _conn = null;

        /// <summary>
        /// 打开指定的路径下的SQLite数据库
        /// </summary>
        /// <param name="path"></param>
        /// <param name="bCreate">是否创建数据库文件</param>
        /// <returns></returns>
        public bool OpenDB(string path, bool bCreate = true)
        {
            if (null != _conn)
            {
                return true;
            }

            try
            {
                if (bCreate)
                {
                    _conn = new SQLiteConnection(path);
                }
                else
                {
                    _conn = new SQLiteConnection(path, SQLiteOpenFlags.ReadOnly);
                }
                
            }
            catch (Exception e)
            {
                throw e;
            }

            return true;
        }

        public void Dispose()
        {
            _conn.Close();
        }

        public bool Insert(T entity)
        {
            if (null == _conn)
            {
                return false;
            }

            try
            {
                _conn.CreateTable<T>();
                _conn.BeginTransaction();
                _conn.Insert(entity);
                _conn.Commit();
            }
            catch (SQLiteException e)
            {
                _conn.Rollback();
                throw new Exception(e.Message);
            }

            return true;
        }

        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public bool Insert(List<T> entities)
        {
            if (null == _conn)
            {
                return false;
            }

            try
            {
                _conn.CreateTable<T>();
                _conn.BeginTransaction();
                foreach (T item in entities)
                {
                    _conn.Insert(item);
                }
                _conn.Commit();
            }
            catch (SQLiteException e)
            {
                _conn.Rollback();
                throw new Exception(e.Message);
            }

            return true;
        }

        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public bool Insert(T[] entities)
        {
            return Insert(entities.ToList<T>());
        }

        public List<T> Query()
        {
            List<T> ret = null;

            if (null != _conn)
            {
                ret = _conn.Table<T>().ToList();
            }

            return ret;
        }
    }
}
